//
//  MainTableViewController.m
//  微博
//
//  Created by zxy on 2018/12/20.
//  Copyright © 2018 zxy. All rights reserved.
//

#import "MainTableViewController.h"
#import "XMGPictureBrowserController.h"
#import "WeiboCell.h"
#import "StatuesModel.h"
#import "SDPhotoBrowser.h"
static NSString *const MainCellId = @"MainCellId";
@interface MainTableViewController ()<SDPhotoBrowserDelegate>{
    StatuesModel *_picM;
}
@property(nonatomic,strong)NSArray *modelArray;
@property(nonatomic,strong)UIView *loadAnimationView;
@end

@implementation MainTableViewController

-(UIView *)loadAnimationView{
    if(!_loadAnimationView){
        _loadAnimationView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
        _loadAnimationView.center = CGPointMake([UIScreen mainScreen].bounds.size.width * 0.5, [UIScreen mainScreen].bounds.size.height * 0.5 - 50);
        [self.view addSubview:_loadAnimationView];
    }
    return _loadAnimationView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"关注";
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor colorWithHexString:@"0xe0e0e0"];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([WeiboCell class]) bundle:nil] forCellReuseIdentifier:MainCellId];
    [self getDatas];
    
    //设置下拉刷新
    [self setupMJRefresh];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(XMGPictureBrower:) name:XMGPictureClickIndexNoticationName object:nil];
}

#pragma mark -进入浏览器页面
-(void)XMGPictureBrower:(NSNotification *)no{
    NSInteger index = [no.userInfo[XMGPictureClickIndexKey] integerValue];
    StatuesModel *model = no.userInfo[XMGPictureClickModelKey];
    //保存点击配图模型
    _picM = model;
//    XMGPictureBrowserController *browser = [[XMGPictureBrowserController alloc]init];
//    browser.currentIndex = index;
//    browser.pictureModel = model;
//    [self presentViewController:browser animated:YES completion:nil];
    SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
    
    //图片的父控件
    browser.sourceImagesContainerView = self.tableView;
    //图片数量
    browser.imageCount = model.big_picUrls.count;
    //当前图片下标
    browser.currentImageIndex = index;
    
    browser.delegate = self;
    
    [browser show]; // 展示图片浏览器
}

#pragma mark -MJRefresh
-(void)setupMJRefresh{
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    self.tableView.mj_header = header;
}

-(void)headerRefresh{
    [self getDatas];
}

// 返回高质量图片的url
- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index
{
    NSString *urlStr = _picM.big_picUrls[index];
    return [NSURL URLWithString:urlStr];
}


#pragma mark -获取数据
-(void)getDatas{
    self.loadAnimationView.hidden = NO;
    [self.loadAnimationView LoadAnimationLayerColor:[UIColor redColor] animationLayerCount:10];
    [StatuesModel getWbDataResult:^(NSArray * _Nonnull modelArr, NSError * _Nonnull error) {
        self.loadAnimationView.hidden = YES;
        self.modelArray = modelArr;
        [self.tableView.mj_header endRefreshing];
        dispatch_group_t group = dispatch_group_create();
        
        //根据url缓存图片，获取缓存图片尺寸,计算cell配图高度
        for (NSInteger i = 0; i < modelArr.count; i++) {
            StatuesModel *model = [modelArr objectAtIndex:i];
            for (NSDictionary *dic in model.pic_urls) {
                NSURL *url = [NSURL URLWithString:dic[@"thumbnail_pic"]];
                dispatch_group_enter(group);
                [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:url options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                    
                } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
                    [[SDImageCache sharedImageCache] storeImage:image forKey:dic[@"thumbnail_pic"] completion:nil];
                    dispatch_group_leave(group);
                }];
            }
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
             [self.tableView reloadData];
        });
        
        
    }];
}



#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    StatuesModel *model = self.modelArray[indexPath.row];
    return  model.cellHeight;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WeiboCell *cell = [tableView dequeueReusableCellWithIdentifier:MainCellId forIndexPath:indexPath];
    cell.model = self.modelArray[indexPath.row];
    return cell;
}


-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
